package com.bwie;



import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description :
 * @Author QiHainan
 * @Create 2025/6/28 11:10
 * @Version 1.0
 */
public class BookList2 {
    private List<Book> bookList = new ArrayList<>();
    private Lock lock = new ReentrantLock();

    public Book addBook(Book book){
        lock.lock();
        bookList.add(book);
        lock.unlock();
        return book;
    }

    public Book getBook(int index){
        lock.lock();
        Book book = bookList.get(index);
        lock.unlock();
        return book;
    }

    public Book removeBook(int index){
        lock.lock();
        Book remove = bookList.remove(index);
        lock.unlock();
        return remove;
    }

    public void printAll(){
        lock.lock();
        for (Book book : bookList) {
            System.out.println(book);
        }
        lock.unlock();
    }

    @Test
    public void testBookList2(){
        BookList2 bookList = new BookList2();

        //添加
        bookList.addBook(new Book("1","title1","author1","publisher1"));
        bookList.addBook(new Book("2","title2","author2","publisher2"));
        bookList.addBook(new Book("3","title3","author3","publisher3"));

        //查找，ID=1
        System.out.println(bookList.getBook(1));

        //删除，ID=1
        bookList.removeBook(1);

        //打印
        bookList.printAll();
    }
}
